{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Memory\n",
    "Let's take a look at what Memory actually looks like in LangChain. Here we'll cover the basics of interacting with an arbitrary memory class.\n",
    "\n",
    "让我们来看看LangChain中的Memory到底是什么样子的，这里我们将介绍与任意内存类交互的基础知识。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'history': \"Human: hi!\\nAI: what's up?\"}"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langchain.memory import ConversationBufferMemory\n",
    "\n",
    "memory = ConversationBufferMemory() # return_str\n",
    "# memory = ConversationBufferMemory(memory_key=\"history\")\n",
    "memory.chat_memory.add_user_message(\"hi!\")\n",
    "memory.chat_memory.add_ai_message(\"what's up?\")\n",
    "\n",
    "# \n",
    "memory.load_memory_variables({})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'history': [HumanMessage(content='hi!'), AIMessage(content=\"what's up?\")]}"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "memory = ConversationBufferMemory(return_messages=True) # return_messages\n",
    "memory.chat_memory.add_user_message(\"hi!\")\n",
    "memory.chat_memory.add_ai_message(\"what's up?\")\n",
    "memory.load_memory_variables({})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new LLMChain chain...\u001b[0m\n",
      "Prompt after formatting:\n",
      "\u001b[32;1m\u001b[1;3mYou are a nice chatbot having a conversation with a human.\n",
      "\n",
      "Previous conversation:\n",
      "\n",
      "\n",
      "New human question: hi\n",
      "Response:\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'question': 'hi', 'chat_history': '', 'text': ' Hello! How can I assist you?'}"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langchain_openai import OpenAI\n",
    "from langchain_core.prompts import PromptTemplate\n",
    "from langchain.chains import LLMChain\n",
    "from langchain.memory import ConversationBufferMemory\n",
    "\n",
    "\n",
    "llm = OpenAI(temperature=0)\n",
    "# Notice that \"chat_history\" is present in the prompt template\n",
    "template = \"\"\"You are a nice chatbot having a conversation with a human.\n",
    "\n",
    "Previous conversation:\n",
    "{chat_history}\n",
    "\n",
    "New human question: {question}\n",
    "Response:\"\"\"\n",
    "prompt = PromptTemplate.from_template(template)\n",
    "# Notice that we need to align the `memory_key`\n",
    "memory = ConversationBufferMemory(memory_key=\"chat_history\")\n",
    "conversation = LLMChain(\n",
    "    llm=llm,\n",
    "    prompt=prompt,\n",
    "    verbose=True,\n",
    "    memory=memory\n",
    ")\n",
    "# Notice that we just pass in the `question` variables - `chat_history` gets populated by memory\n",
    "conversation.invoke({\"question\": \"hi\"})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new LLMChain chain...\u001b[0m\n",
      "Prompt after formatting:\n",
      "\u001b[32;1m\u001b[1;3mSystem: You are a nice chatbot having a conversation with a human.\n",
      "Human: hi\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'question': 'hi',\n",
       " 'chat_history': [HumanMessage(content='hi'),\n",
       "  AIMessage(content='Hello! How are you doing today?')],\n",
       " 'text': 'Hello! How are you doing today?'}"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langchain_openai import ChatOpenAI\n",
    "from langchain_core.prompts import (\n",
    "    ChatPromptTemplate,\n",
    "    MessagesPlaceholder,\n",
    "    SystemMessagePromptTemplate,\n",
    "    HumanMessagePromptTemplate,\n",
    ")\n",
    "from langchain.chains import LLMChain\n",
    "from langchain.memory import ConversationBufferMemory\n",
    "\n",
    "\n",
    "llm = ChatOpenAI()\n",
    "prompt = ChatPromptTemplate(\n",
    "    messages=[\n",
    "        SystemMessagePromptTemplate.from_template(\n",
    "            \"You are a nice chatbot having a conversation with a human.\"\n",
    "        ),\n",
    "        # The `variable_name` here is what must align with memory\n",
    "        MessagesPlaceholder(variable_name=\"chat_history\"),\n",
    "        HumanMessagePromptTemplate.from_template(\"{question}\")\n",
    "    ]\n",
    ")\n",
    "# Notice that we `return_messages=True` to fit into the MessagesPlaceholder\n",
    "# Notice that `\"chat_history\"` aligns with the MessagesPlaceholder name.\n",
    "memory = ConversationBufferMemory(memory_key=\"chat_history\", return_messages=True)\n",
    "conversation = LLMChain(\n",
    "    llm=llm,\n",
    "    prompt=prompt,\n",
    "    verbose=True,\n",
    "    memory=memory\n",
    ")\n",
    "\n",
    "# Notice that we just pass in the `question` variables - `chat_history` gets populated by memory\n",
    "conversation({\"question\": \"hi\"})"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "langchain0_1",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
